<template>
  <div class="echarts-container">
    <!-- 导航按钮 -->
    <div class="nav_btn">
      <div v-for="n, index in thatTime" :key="n.value">
        <el-button :type="index == NavActive ? 'primary' : ''" @click="changeTab(index)" v-show="!n.disabled">
          {{ n.name }}
        </el-button>
      </div>
    </div>
    
     <!-- 图表容器 -->
     <div v-if="hourlyVisitData && hourlyVisitData.length > 0" ref="chart" class="chart-wrapper"></div>

     <!-- 加载状态 -->
     <div v-else-if="loading" class="loading-data">
       <i class="el-icon-loading loading-icon"></i>
       <p class="loading-text">数据加载中...</p>
     </div>

     <!-- 空数据状态 -->
     <div v-else class="empty-data">
       <i class="el-icon-data-line empty-icon"></i>
       <p class="empty-text">暂无数据</p>
     </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getVisitFunctionTrendData } from '@/api/chenlong.js'
export default {
  name: 'EChartsChart',  //访问核心功能趋势
  props: {
    options: {
      type: Object,
      default: () => ({})
    },
    corpId: {
      type: String,
      default: ''
    },
    dateRange: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null, // 图表实例
      thatTime: [
        // { name: '功能筛选', disabled: false },
        { name: '患者信息管理',value:1, disabled: false },
        { name: '分类标签管理',value:2, disabled: false },
        { name: '患者主动关怀',value:3, disabled: false },
        { name: '患者口碑',value:4, disabled: false },
        { name: '我的团队',value:6, disabled: false },
        { name: '数字专属码',value:7, disabled: false },
        { name: '诊后随访',value:8, disabled: false },
        { name: '复诊预约',value:12, disabled: false },
        { name: '素材管理',value:9, disabled: false },
        { name: '健康科普',value:11, disabled: false },
        { name: '问卷管理',value:10, disabled: false },
      ],
      NavActive: 0,
      hourlyVisitData: [],
      loading: false
    }
  },
  watch: {
    corpId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.gentCurrentData()  // corpId变化时更新数据
          this.updateChart()
        }
      }
    },
    dateRange: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.gentCurrentData()
          this.updateChart()
        }
      }
    }
  },
   mounted() {
     // 获取数据
     this.gentCurrentData()
     this.$emit('exportData', this.thatTime[this.NavActive].value)
     // 监听窗口大小变化，自适应图表
     window.addEventListener('resize', this.handleResize)
   },
   beforeDestroy() {
     // 销毁图表实例，释放资源
     if (this.chart) {
       this.chart.dispose()
     }
     // 移除事件监听
     window.removeEventListener('resize', this.handleResize)
   },
  methods: {
    changeTab(index) {
      if (this.NavActive == index) return
      this.NavActive = index
      this.$emit('exportData', this.thatTime[index].value)
      this.gentCurrentData()
      // 根据选择的指标更新图表
      this.updateChart()
    },
    
    updateChart() {
      // 根据NavActive更新图表数据
      if (this.chart) {
        // 这里可以根据NavActive更新图表配置
        this.chart.setOption(this.getChartOptions())
      }
    },
    
    getChartOptions() {
      // 根据NavActive返回不同的图表配置
      const baseOptions = {
        tooltip: {
          trigger: 'axis'
        },
        color: ['#00cf8a', '#6184fb', '#faa52d'], // 全局颜色：对应"今日""1天前""7天前"
        legend: {
          data: [],
          bottom: '0',
          icon: 'circle', // 图标形状为圆形
          itemWidth: 8, 
          show:false,  // 圆点大小
          itemHeight: 8   // 圆点大小（与宽度一致保持圆形）
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '12%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.getXAxisData()
        },
        yAxis: {
          type: 'value'
        },
        series: this.getSeriesData()
      }
      return baseOptions
    },
    
    getXAxisData() {
       // 根据数据返回x轴数据
       if (this.hourlyVisitData && this.hourlyVisitData.length > 0) {
        return this.hourlyVisitData.reduce((pre, value, index) => {
          if (value.formatted_date || value.day_of_week) {
            pre.push(value.day_of_week + value.formatted_date)
          }
          return pre
        }, [])
      }
      return []
    },
    
    getSeriesData() {
      // 根据NavActive返回不同的数据系列
      const series = []
      
      if (this.hourlyVisitData && this.hourlyVisitData.length > 0) {
        // 根据NavActive选择不同的数据字段
        let dataField = 'visitCount' // 默认访问人数
        switch(this.NavActive) {
          case 1: // 消息通知
            dataField = 'messageCount'
            break
          case 2: // 工作台
            dataField = 'workbenchCount'
            break
          case 3: // 通讯录
            dataField = 'contactCount'
            break
          case 4: // 日程安排
            dataField = 'scheduleCount'
            break
          case 5: // 文件管理
            dataField = 'fileCount'
            break
          case 6: // 审批流程
            dataField = 'approvalCount'
            break
          default:
            dataField = 'visitCount'
        }
        
        const data = this.hourlyVisitData.map(item => item.count || 0)
        
        // 定义绿色渐变阴影
        const greenGradient = {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(129, 227, 153, 0.6)' }, // 淡绿色，透明度60%
            { offset: 1, color: 'rgba(129, 227, 153, 0)' }   // 完全透明
          ]
        }
        
        series.push({
          name: this.thatTime[this.NavActive]?.name || '访问数据',
          type: 'line',
          data: data,
          smooth: true,
          showSymbol: false, // 去掉数据点
          areaStyle: {
            color: greenGradient // 添加渐变阴影
          },
          lineStyle: {
            width: 2, // 线条宽度
            color: '#00cf8a' // 线条颜色
          }
        })
      } else {
        // 没有数据时显示空图表
        series.push({
          name: this.thatTime[this.NavActive]?.name || '访问数据',
          type: 'line',
          data: [],
          smooth: true,
          showSymbol: false,
          areaStyle: {
            color: 'rgba(129, 227, 153, 0.6)'
          },
          lineStyle: {
            width: 2,
            color: '#00cf8a'
          }
        })
      }
      
      return series
    },
    
    dateRangeToTime(time) {
      const timeObj = new Date(time)
      return this.formatDateForApi(timeObj)
    },
    formatDateForApi(date) {
      // 格式化日期为API需要的格式
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    },
     async gentCurrentData() { // 获取数据
       try {
         // 开始加载，清空数据，显示加载状态
         this.loading = true
         this.hourlyVisitData = []
         
         // 统一处理时间参数
         let startTime, endTime
         if (this.dateRange && Array.isArray(this.dateRange) && this.dateRange.length >= 2) {
           startTime = this.dateRangeToTime(this.dateRange[0])
           endTime = this.dateRangeToTime(this.dateRange[1])
         } else {
           // 如果没有传递时间范围，使用默认值（最近7天）
           const today = new Date()
           const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
           startTime = this.formatDateForApi(sevenDaysAgo)
           endTime = this.formatDateForApi(today)
         }
         
         const params = {
           corpId: this.corpId,
           startTime,
           endTime,
           type: this.thatTime[this.NavActive].value
         }
         
         const res = await getVisitFunctionTrendData(params)
         console.log('接口返回:', res)
         
         if (res.code == 200 && res.data && Array.isArray(res.data) && res.data.length > 0) {
           this.hourlyVisitData = res.data
           console.log("数据长度:", this.hourlyVisitData.length)

           // 数据更新后重新渲染图表
           this.$nextTick(() => {
             if (this.hourlyVisitData && this.hourlyVisitData.length > 0) {
               this.initChart()
             }
           })
         } else {
           // 接口返回错误或无数据时，清空数据
           this.hourlyVisitData = []
           console.log('接口返回错误或无数据，已清空数据')
         }
       } catch (error) {
         console.error('获取数据失败:', error)
         this.hourlyVisitData = []
       } finally {
         // 无论成功还是失败，都结束加载状态
         this.loading = false
       }
     },
    
     initChart() {
       // 销毁已存在的图表实例
       if (this.chart) {
         this.chart.dispose()
         this.chart = null
       }
       
       // 确保DOM元素存在
       if (this.$refs.chart) {
         // 初始化图表实例
         this.chart = echarts.init(this.$refs.chart)
         
         // 设置初始图表配置
         this.chart.setOption(this.getChartOptions())
       }
     },
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.echarts-container {
  width: 100%;
  padding: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 300px; /* 必须设置高度，否则图表不显示 */
}

.nav_btn {
  width: 360px;
  display: flex;
  justify-content: space-between;
  flex-shrink: 0;
  margin-bottom: 16px;
}

.nav_btn .el-button {
  margin-right: 8px;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999999;
  height: 300px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-text {
  margin: 0;
  font-size: 14px;
  color: #999999;
}

.loading-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999999;
  height: 300px;
}

.loading-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #409eff;
  animation: rotate 2s linear infinite;
}

.loading-text {
  margin: 0;
  font-size: 14px;
  color: #666666;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
